package com.cosytek.farmmanager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by Happy on 2015/4/11.
 */
public class MsgFragmentAdapter extends BaseAdapter {

    private static final String TAG = "MsgFragmentAdapter";

    public MsgFragmentAdapter(LayoutInflater inflater) {
        viewInflater = inflater;
    }
    private final LayoutInflater viewInflater;

    private ArrayList<MsgManager.Msg> msgArrayList = new ArrayList<MsgManager.Msg>();

    private int totalRecord;
    @Override
    public int getCount() {
        return totalRecord = MsgManager.instance().getTotalMsgCount();
    }

    private MsgManager.Msg loadMsg(int position) {
        int x = msgArrayList.size();
        while (x <= position) {
            MsgManager.Msg msg = MsgManager.instance().loadMessage(totalRecord - x -1, 1);
            Log.d(TAG, String.format("msg pos:%d, id:%d, title:%s", x, msg.id(), msg.title()));
            msgArrayList.add(msg);
            x++;
        }

        return msgArrayList.get(position);
    }

    @Override
    public Object getItem(int position) {
        MsgManager.Msg msg = loadMsg(position);
        return msg;
    }

    @Override
    public long getItemId(int position) {
        MsgManager.Msg msg = loadMsg(position);
        if (msg == null) {
            return 0;
        }
        return msg.id();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (convertView == null) {
            convertView = viewInflater.inflate(R.layout.frag_msg_list_item, null);
            vh = new ViewHolder();
            vh.mTitleView = (TextView)convertView.findViewById(R.id.frag_msg_item_title);
            vh.mAbstractView = (TextView)convertView.findViewById(R.id.frag_msg_item_content);

            convertView.setTag(vh);
        } else {
            vh = (ViewHolder)convertView.getTag();
        }

        MsgManager.Msg msg = loadMsg(position);
        vh.mTitleView.setText(msg.title());
        vh.mAbstractView.setText(msg.abstracts());

        if (msg.flag() == 0) {
            MsgManager.instance().markMsgRead(msg.id());
            msg.setFlag(1);
        }
        return convertView;
    }

    public void invalidate() {
        msgArrayList.clear();
        notifyDataSetChanged();
    }

    private class ViewHolder {
        public TextView mTitleView;
        public TextView mAbstractView;
    }
}
